<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="80%" size="large">
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px" v-loading="formLoading" :disabled="formType === 'detail'">
      <el-tabs v-model="activeTab" type="border-card">
        <!-- 基础信息 -->
        <el-tab-pane label="基础信息" name="basic">
           <!-- 离职状态警告(仅在查看详情且员工已离职时显示) -->
          <el-alert
            v-if="formType === 'detail' && formData.employeeStatus === 1"
            title="该员工已离职"
            type="warning"
            :closable="false"
            show-icon
            style="margin-bottom: 20px;"
          >
            <template #default>
              <div style="font-size: 14px; font-weight: bold;">
                离职日期: {{ formatDate(formData.endDate) }}
              </div>
            </template>
          </el-alert>
          <el-row>
            <el-col :span="8">
              <el-form-item label="员工编号" prop="userCode">
                <el-input v-model="formData.userCode" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="员工姓名" prop="realName">
                <el-input v-model="formData.realName" placeholder="请输入员工姓名" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="性别" prop="gender">
                <el-select v-model="formData.gender" placeholder="请选择性别" disabled>
                  <el-option
                    v-for="dict in getIntDictOptions(DICT_TYPE.SYSTEM_USER_SEX)" :key="dict.value"
                    :label="dict.label" :value="dict.value" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="8">
              <el-form-item label="联系电话" prop="phone">
                <el-input v-model="formData.phone" placeholder="请输入联系电话" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="民族" prop="ethnicGroup">
                <el-input v-model="formData.ethnicGroup" placeholder="请输入民族" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="籍贯" prop="nativePlace">
                <el-input v-model="formData.nativePlace" placeholder="请输入籍贯" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="8">
              <el-form-item label="出生日期" prop="birthDate">
                <el-date-picker v-model="formData.birthDate" type="date" value-format="x" placeholder="选择出生日期" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="身份证号码" prop="idCard">
                <el-input v-model="formData.idCard" placeholder="请输入身份证号码" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="最高学历" prop="highestDegree">
                <el-input v-model="formData.highestDegree" placeholder="请输入最高学历" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="8">
              <el-form-item label="学历分值" prop="educationScore">
                <el-input v-model="formData.educationScore" placeholder="请输入学历分值" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="紧急联系人" prop="emergencyContact">
                <el-input v-model="formData.emergencyContact" placeholder="请输入紧急联系人" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="紧急手机号码" prop="emergencyContactPhone">
                <el-input v-model="formData.emergencyContactPhone" placeholder="请输入紧急联系人手机号码" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="户籍地址" prop="householdLocation">
            <el-input v-model="formData.householdLocation" placeholder="请输入户口所在地" />
          </el-form-item>
          
          <el-form-item label="现居地址" prop="currentAddress">
            <el-input v-model="formData.currentAddress" placeholder="请输入现住地址" />
          </el-form-item>

          <el-row>
            <el-col :span="8">
              <el-form-item label="会计证书" prop="accountingIntermediate">
                <el-select v-model="formData.accountingIntermediate" placeholder="请选择会计证书">
                  <el-option value="无" label="无" />
                  <el-option value="初级" label="初级" />
                  <el-option value="中级" label="中级" />
                  <el-option value="高级" label="高级" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="计算机证书" prop="computerCertificate">
                <el-select v-model="formData.computerCertificate" placeholder="请选择计算机证书">
                  <el-option value="无" label="无" />
                  <el-option value="一级" label="一级" />
                  <el-option value="二级" label="二级" />
                  <el-option value="三级" label="三级" />
                  <el-option value="四级" label="四级" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="婚姻状况" prop="maritalStatus">
                <el-select v-model="formData.maritalStatus" placeholder="请选择婚姻状况">
                  <el-option
                    v-for="dict in getIntDictOptions(DICT_TYPE.OA_MARITAL_STATUS)" :key="dict.value"
                    :label="dict.label" :value="dict.value" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="所获其它证书" prop="otherCertificates">
            <el-input v-model="formData.otherCertificates" placeholder="请输入" type="textarea" />
          </el-form-item>
          
          <el-form-item label="其它备注" prop="employeeIntro">
            <el-input v-model="formData.employeeIntro" placeholder="请输入其它备注" type="textarea" />
          </el-form-item>
        </el-tab-pane>

        <!-- 入职信息 -->
        <el-tab-pane label="入职信息" name="employment"> 
          <el-row>
            <el-col :span="8">
              <el-form-item label="所在部门" prop="deptName">
                <el-input v-model="formData.deptName" placeholder="请输入所在部门" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="岗位" prop="position">
                <el-input v-model="formData.position" placeholder="请输入岗位" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="员工类型" prop="employeeType">
                <el-select v-model="formData.employeeType" placeholder="请选择员工类型">
                  <el-option
                    v-for="dict in getIntDictOptions(DICT_TYPE.OA_EMPLOYEE_TYPE)" :key="dict.value"
                    :label="dict.label" :value="dict.value" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="8">
              <el-form-item label="入职日期" prop="hireDate">
                <el-date-picker v-model="formData.hireDate" type="date" value-format="x" placeholder="选择入职日期" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="入职年限" prop="workYears">
                <el-input v-model="workYears" placeholder="自动计算" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="试用期开始时间" prop="probationStartDate">
                <el-date-picker v-model="formData.probationStartDate" type="date" value-format="x" placeholder="选择试用期开始时间" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="8">
              <el-form-item label="试用期结束时间" prop="probationEndDate">
                <el-date-picker v-model="formData.probationEndDate" type="date" value-format="x" placeholder="选择试用期结束时间" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="试用期剩余天数" prop="probationRemainingDays">
                <el-input v-model="probationRemainingDays" placeholder="自动计算" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="社保缴纳公司" prop="socialSecurityCompany">
                <el-input v-model="formData.socialSecurityCompany" placeholder="请输入社保缴纳公司" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="8">
              <el-form-item label="工资卡开户行" prop="bankName">
                <el-input v-model="formData.bankName" placeholder="请输入工资卡开户行" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="工资卡帐号" prop="bankAccount">
                <el-input v-model="formData.bankAccount" placeholder="请输入工资卡帐号" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-tab-pane>

        <!-- 员工工资标准 -->
        <el-tab-pane label="员工工资标准" name="salary">
          <el-row>
            <el-col :span="8">
              <el-form-item label="基本工资" prop="baseSalary">
                <el-input-number v-model="formData.baseSalary" :min="0" :precision="2" :step="100" placeholder="请输入基本工资" style="width: 100%;" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="岗位工资" prop="positionSalary">
                <el-input-number v-model="formData.positionSalary" :min="0" :precision="2" :step="100" placeholder="请输入岗位工资" style="width: 100%;" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="绩效工资基数" prop="performanceSalaryBase">
                <el-input-number v-model="formData.performanceSalaryBase" :min="0" :precision="2" :step="100" placeholder="请输入绩效工资基数" style="width: 100%;" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="试用期工资" prop="probationSalary">
                <el-input-number v-model="formData.probationSalary" :min="0" :precision="2" :step="100" placeholder="请输入试用期工资" style="width: 100%;" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="其他工资" prop="otherSalary">
                <el-input-number v-model="formData.otherSalary" :min="0" :precision="2" :step="100" placeholder="请输入其他工资" style="width: 100%;" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-tab-pane>

        <!-- 员工合同 -->
        <el-tab-pane label="员工合同" name="contract">
          <EmployeeContracts :user-id="formData.userId"  />
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" v-if="formType!='detail'" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { EmployeeArchiveApi, EmployeeArchiveVO } from '@/api/oa/employeearchive'
import EmployeeContracts from '@/views/oa/employeecontracts/index.vue'
// import Employeeleavebalance from '@/views/oa/employeeleavebalance/index.vue'
// import { generateEmployeeLeaveBalance } from '@/api/oa/employeeleavebalance'
// import { fromType } from 'vue-types'

/** 员工档案 表单 */
defineOptions({ name: 'EmployeeArchiveForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const activeTab = ref('basic') // 当前激活的Tab

const formData = ref({
  id: undefined,
  phone: undefined,
  userId: undefined,
  realName: undefined,
  userName: undefined,
  userCode: undefined,
  gender: undefined,
  birthDate: undefined,
  politicalStatus: undefined,
  ethnicGroup: undefined,
  householdType: undefined,
  idCard: undefined,
  maritalStatus: undefined,
  nativePlace: undefined,
  householdLocation: undefined,
  graduateInstitution: undefined,
  highestDegree: undefined,
  educationScore: undefined,
  major: undefined,
  graduationDate: undefined,
  employeeStatus: 0, // 默认为0在职
  homeAddress: undefined,
  currentAddress: undefined,
  emergencyContactPhone: undefined,
  emergencyContact: undefined,
  accountingIntermediate: undefined,
  computerCertificate: undefined,
  otherCertificates: undefined,
  employeeType: undefined,
  hireDate: undefined,
  endDate: undefined,
  workStartDate: undefined,
  probationStartDate: undefined,
  probationEndDate: undefined,
  bankName: undefined,
  bankAccount: undefined,
  socialSecurityNumber: undefined,
  housingFundNumber: undefined,
  socialSecurityCompany: undefined,
  position: undefined,
  employeeIntro: undefined,
  appendix: undefined,
  deptName: undefined,
  baseSalary: undefined,
  positionSalary: undefined,
  probationSalary: undefined,
  performanceSalaryBase: undefined,
  otherSalary: undefined,
})

const formRules = reactive({
  realName: [{ required: true, message: '员工表id不能为空', trigger: 'blur' }],
  // hireDate: [{ required: true, message: '入职日期不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

// 格式化日期为 YYYY-MM-DD
const formatDate = (date: any) => {
  if (!date) {
    return ''
  }

  try {
    let dateObj: Date
    if (typeof date === 'string') {
      dateObj = new Date(date)
    } else if (typeof date === 'number') {
      dateObj = new Date(date)
    } else {
      dateObj = date
    }

    if (isNaN(dateObj.getTime())) {
      return ''
    }

    const year = dateObj.getFullYear()
    const month = String(dateObj.getMonth() + 1).padStart(2, '0')
    const day = String(dateObj.getDate()).padStart(2, '0')
    return `${year}-${month}-${day}`
  } catch (error) {
    console.error('格式化日期时出错:', error)
    return ''
  }
}

// 计算入职年限
const workYears = computed(() => {
  if (!formData.value.hireDate) {
    return ''
  }

  try {
    // 处理不同的时间格式
    let hireDate: Date
    const hireDateValue = formData.value.hireDate

    if (typeof hireDateValue === 'string') {
      // 如果是字符串格式，直接创建Date对象
      hireDate = new Date(hireDateValue)
    } else if (typeof hireDateValue === 'number') {
      // 如果是数字格式（时间戳），创建Date对象
      hireDate = new Date(hireDateValue)
    } else {
      // 如果已经是Date对象
      hireDate = hireDateValue
    }

    // 检查日期是否有效
    if (isNaN(hireDate.getTime())) {
      return ''
    }

    const currentDate = new Date()
    const diffTime = Math.abs(currentDate.getTime() - hireDate.getTime())
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
    const years = (diffDays / 365).toFixed(1)

    return `${years} 年`
  } catch (error) {
    console.error('计算入职年限时出错:', error)
    return ''
  }
})

// 计算试用期剩余天数
const probationRemainingDays = computed(() => {
  if (!formData.value.probationEndDate) {
    return ''
  }

  try {
    // 处理不同的时间格式
    let probationEndDate: Date
    const probationEndDateValue = formData.value.probationEndDate

    if (typeof probationEndDateValue === 'string') {
      // 如果是字符串格式，直接创建Date对象
      probationEndDate = new Date(probationEndDateValue)
    } else if (typeof probationEndDateValue === 'number') {
      // 如果是数字格式（时间戳），创建Date对象
      probationEndDate = new Date(probationEndDateValue)
    } else {
      // 如果已经是Date对象
      probationEndDate = probationEndDateValue
    }

    // 检查日期是否有效
    if (isNaN(probationEndDate.getTime())) {
      return ''
    }

    const currentDate = new Date()
    // 设置时间为当天的开始时间（00:00:00）
    currentDate.setHours(0, 0, 0, 0)
    probationEndDate.setHours(0, 0, 0, 0)

    // 计算剩余天数
    const diffTime = probationEndDate.getTime() - currentDate.getTime()
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))

    if (diffDays < 0) {
      return `已过期 ${Math.abs(diffDays)} 天`
    } else if (diffDays === 0) {
      return '今天到期'
    } else {
      return `剩余 ${diffDays} 天`
    }
  } catch (error) {
    console.error('计算试用期剩余天数时出错:', error)
    return ''
  }
})

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  activeTab.value = 'basic' // 重置到第一个Tab
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {

      const employeeArchiveInfo = await EmployeeArchiveApi.getEmployeeArchive(id)
      if(employeeArchiveInfo.userId){
        const userInfo = await EmployeeArchiveApi.getUserInfo(employeeArchiveInfo.userId)
        const mergedInfo = { ...userInfo, ...employeeArchiveInfo }
        mergedInfo.id = employeeArchiveInfo.id
        formData.value = mergedInfo
      }else{
        formData.value = employeeArchiveInfo
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as EmployeeArchiveVO
    if (formType.value === 'create') {
      await EmployeeArchiveApi.createEmployeeArchive(data)
      message.success(t('common.createSuccess'))
    } else {
      await EmployeeArchiveApi.updateEmployeeArchive(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    phone: undefined,
    userId: undefined,
    realName: undefined,
    userName: undefined,
    userCode: undefined,
    gender: undefined,
    birthDate: undefined,
    politicalStatus: undefined,
    ethnicGroup: undefined,
    householdType: undefined,
    idCard: undefined,
    maritalStatus: undefined,
    nativePlace: undefined,
    householdLocation: undefined,
    graduateInstitution: undefined,
    highestDegree: undefined,
    educationScore: undefined,
    major: undefined,
    graduationDate: undefined,
    employeeStatus: 0, // 默认为0在职
    homeAddress: undefined,
    currentAddress: undefined,
    emergencyContactPhone: undefined,
    emergencyContact: undefined,
    accountingIntermediate: undefined,
    computerCertificate: undefined,
    otherCertificates: undefined,
    employeeType: undefined,
    hireDate: undefined,
    endDate: undefined,
    workStartDate: undefined,
    probationStartDate: undefined,
    probationEndDate: undefined,
    bankName: undefined,
    bankAccount: undefined,
    socialSecurityNumber: undefined,
    housingFundNumber: undefined,
    socialSecurityCompany: undefined,
    position: undefined,
    employeeIntro: undefined,
    appendix: undefined,
    deptName: undefined,
    baseSalary: undefined,
    positionSalary: undefined,
    probationSalary: undefined,
    performanceSalaryBase: undefined,
    otherSalary: undefined,
  } as typeof formData.value
  formRef.value?.resetFields()
}
</script>
